import { ExtendedApiClient } from './api'
import {
    EnhancedMockDataGenerator,
    MOCK_SCENARIOS,
    MockDataConfig
} from '@/utils/enhancedMockData'
import { useDevToolsStore } from '@/stores/devToolsStore'
import {
    Dataset,
    CreateDatasetRequest,
    UpdateDatasetRequest,
    DatasetStats
} from '@/types/dataset'
import { ImageData, ImageMetadata } from '@/types/image'
import {
    Task,
    TaskResult,
    TaskStatusInfo,
    TaskParams,
    CreateTaskRequest,
    UpdateTaskRequest
} from '@/types/task'
import { PaginatedResponse } from '@/types/api'
import { PaginationOption } from '@/types/common'

// 增强的模拟API客户端
class EnhancedMockApiClient implements ExtendedApiClient {
    private dataGenerator: EnhancedMockDataGenerator
    private datasets: Map<string, Dataset> = new Map()
    private taskResults: Map<string, TaskResult[]> = new Map()

    constructor() {
        this.dataGenerator = new EnhancedMockDataGenerator()
        this.initializeData()
    }

    // 初始化数据
    private initializeData() {
        const datasets = this.dataGenerator.generateDatasets()
        datasets.forEach(dataset => {
            this.datasets.set(dataset.id, dataset)
        })
    }

    // 获取当前模拟数据模式
    private getCurrentConfig(): MockDataConfig {
        if (typeof window !== 'undefined') {
            const devStore = useDevToolsStore.getState()
            const scenarioConfig = MOCK_SCENARIOS[devStore.mockDataMode as keyof typeof MOCK_SCENARIOS]
            return scenarioConfig || MOCK_SCENARIOS.default
        }
        return MOCK_SCENARIOS.default
    }

    // 更新数据生成器配置
    private updateGeneratorConfig() {
        const config = this.getCurrentConfig()
        this.dataGenerator.updateConfig(config)

        // 重新生成数据
        if (config.mode === 'empty') {
            this.datasets.clear()
        } else {
            this.initializeData()
        }
    }

    // 模拟网络延迟
    private async simulateDelay(): Promise<void> {
        const config = this.getCurrentConfig()
        let delay = 200

        switch (config.mode) {
            case 'slow':
                delay = 2000 + Math.random() * 3000 // 2-5秒
                break
            default:
                delay = 200 + Math.random() * 300 // 200-500ms
        }

        return new Promise(resolve => setTimeout(resolve, delay))
    }

    // 模拟错误场景
    private simulateError(operation: string): void {
        const config = this.getCurrentConfig()
        if (config.mode === 'error' && Math.random() < 0.3) { // 30% 错误率
            throw new Error(`Mock API Error: ${operation} failed in error simulation mode`)
        }
    }

    // 数据集相关方法
    async getDatasets(): Promise<Dataset[]> {
        await this.simulateDelay()
        this.simulateError('getDatasets')
        this.updateGeneratorConfig()

        return Array.from(this.datasets.values())
    }

    async getDataset(id: string): Promise<Dataset> {
        await this.simulateDelay()
        this.simulateError('getDataset')

        const dataset = this.datasets.get(id)
        if (!dataset) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        return { ...dataset }
    }

    async createDataset(data: CreateDatasetRequest): Promise<Dataset> {
        await this.simulateDelay()
        this.simulateError('createDataset')

        const newId = `mock_${Date.now()}`
        const newDataset = this.dataGenerator.generateDataset(newId, data.type)

        // 应用用户提供的数据
        newDataset.name = data.name
        newDataset.description = data.description
        newDataset.tags = data.tags || []
        newDataset.isPublic = data.isPublic || false

        this.datasets.set(newId, newDataset)
        return { ...newDataset }
    }

    async updateDataset(id: string, data: UpdateDatasetRequest): Promise<Dataset> {
        await this.simulateDelay()
        this.simulateError('updateDataset')

        const dataset = this.datasets.get(id)
        if (!dataset) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        const updatedDataset = {
            ...dataset,
            ...data,
            updatedAt: new Date()
        }

        this.datasets.set(id, updatedDataset)
        return { ...updatedDataset }
    }

    async deleteDataset(id: string): Promise<void> {
        await this.simulateDelay()
        this.simulateError('deleteDataset')

        if (!this.datasets.has(id)) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        this.datasets.delete(id)
        this.taskResults.delete(id)
    }

    async getDatasetStats(id: string): Promise<DatasetStats> {
        await this.simulateDelay()
        this.simulateError('getDatasetStats')

        const dataset = this.datasets.get(id)
        if (!dataset) {
            throw new Error(`Dataset with id ${id} not found`)
        }

        const config = this.getCurrentConfig()

        return {
            totalImages: dataset.imageCount,
            totalSize: dataset.size,
            imageFormats: { 'DICOM': dataset.imageCount },
            modalities: {
                [dataset.type === '3D' ? 'CT' : 'CR']: dataset.imageCount
            },
            lastUpdated: dataset.updatedAt,
            // 额外统计信息
            ...(config.mode === 'large' && {
                processingStats: {
                    totalProcessingTime: 3600000, // 1小时
                    averageProcessingTime: 72000, // 2分钟
                    successRate: 0.95
                },
                qualityMetrics: {
                    averageQuality: 0.87,
                    qualityDistribution: {
                        excellent: 0.3,
                        good: 0.5,
                        fair: 0.15,
                        poor: 0.05
                    }
                }
            })
        }
    }

    async getDatasetsWithPagination(pagination?: PaginationOption): Promise<PaginatedResponse<Dataset>> {
        await this.simulateDelay()
        this.simulateError('getDatasetsWithPagination')

        const allDatasets = Array.from(this.datasets.values())
        const page = pagination?.page || 1
        const pageSize = pagination?.pageSize || 10
        const startIndex = (page - 1) * pageSize
        const endIndex = startIndex + pageSize

        const items = allDatasets.slice(startIndex, endIndex)

        return {
            items,
            total: allDatasets.length,
            page,
            pageSize,
            hasNext: endIndex < allDatasets.length,
            hasPrev: page > 1
        }
    }

    // 影像数据相关方法
    async getImageData(imageId: string): Promise<ImageData> {
        await this.simulateDelay()
        this.simulateError('getImageData')

        // 查找包含该图像的数据集
        for (const dataset of this.datasets.values()) {
            const image = dataset.images.find(img => img.id === imageId)
            if (image) {
                return { ...image }
            }
        }

        throw new Error(`Image with id ${imageId} not found`)
    }

    async getImageMetadata(imageId: string): Promise<ImageMetadata> {
        await this.simulateDelay()
        this.simulateError('getImageMetadata')

        const imageData = await this.getImageData(imageId)
        return imageData.metadata || {}
    }

    async uploadImages(datasetId: string, files: File[]): Promise<ImageData[]> {
        await this.simulateDelay()
        this.simulateError('uploadImages')

        const dataset = this.datasets.get(datasetId)
        if (!dataset) {
            throw new Error(`Dataset with id ${datasetId} not found`)
        }

        const uploadedImages = files.map((file, index) => {
            const imageId = `${datasetId}_upload_${Date.now()}_${index}`
            return this.dataGenerator.generateImageData(imageId, dataset.type)
        })

        // 更新数据集
        dataset.images.push(...uploadedImages)
        dataset.imageCount += uploadedImages.length
        dataset.updatedAt = new Date()

        this.datasets.set(datasetId, dataset)

        return uploadedImages
    }

    async deleteImages(imageIds: string[]): Promise<void> {
        await this.simulateDelay()
        this.simulateError('deleteImages')

        for (const dataset of this.datasets.values()) {
            dataset.images = dataset.images.filter(img => !imageIds.includes(img.id))
            dataset.imageCount = dataset.images.length
        }
    }

    // 任务相关方法
    async getTasks(datasetId: string): Promise<Task[]> {
        await this.simulateDelay()
        this.simulateError('getTasks')

        const dataset = this.datasets.get(datasetId)
        if (!dataset) {
            throw new Error(`Dataset with id ${datasetId} not found`)
        }

        return [...dataset.tasks]
    }

    async createTask(data: CreateTaskRequest): Promise<Task> {
        await this.simulateDelay()
        this.simulateError('createTask')

        const dataset = this.datasets.get(data.datasetId)
        if (!dataset) {
            throw new Error(`Dataset with id ${data.datasetId} not found`)
        }

        const newTask: Task = {
            id: `task_${Date.now()}`,
            name: data.name,
            type: data.type,
            description: data.description,
            config: data.config,
            status: 'idle',
            datasetId: data.datasetId,
            priority: data.priority || 1,
            createdAt: new Date(),
            updatedAt: new Date()
        }

        dataset.tasks.push(newTask)
        this.datasets.set(data.datasetId, dataset)

        return { ...newTask }
    }

    async updateTask(id: string, data: UpdateTaskRequest): Promise<Task> {
        await this.simulateDelay()
        this.simulateError('updateTask')

        for (const dataset of this.datasets.values()) {
            const taskIndex = dataset.tasks.findIndex(t => t.id === id)
            if (taskIndex !== -1) {
                const updatedTask = {
                    ...dataset.tasks[taskIndex],
                    ...data,
                    config: {
                        ...dataset.tasks[taskIndex].config,
                        ...data.config,
                        parameters: data.config?.parameters || dataset.tasks[taskIndex].config.parameters || {}
                    },
                    updatedAt: new Date()
                }

                dataset.tasks[taskIndex] = updatedTask
                return { ...updatedTask }
            }
        }

        throw new Error(`Task with id ${id} not found`)
    }

    async deleteTask(id: string): Promise<void> {
        await this.simulateDelay()
        this.simulateError('deleteTask')

        for (const dataset of this.datasets.values()) {
            const taskIndex = dataset.tasks.findIndex(t => t.id === id)
            if (taskIndex !== -1) {
                dataset.tasks.splice(taskIndex, 1)
                return
            }
        }

        throw new Error(`Task with id ${id} not found`)
    }

    async startTask(taskId: string, params: TaskParams): Promise<TaskResult> {
        await this.simulateDelay()
        this.simulateError('startTask')

        // 查找任务
        let task: Task | undefined
        for (const dataset of this.datasets.values()) {
            task = dataset.tasks.find(t => t.id === taskId)
            if (task) break
        }

        if (!task) {
            throw new Error(`Task with id ${taskId} not found`)
        }

        // 生成任务结果
        const result = this.dataGenerator.generateTaskResult(taskId, task.type)

        // 存储结果
        const existingResults = this.taskResults.get(taskId) || []
        existingResults.push(result)
        this.taskResults.set(taskId, existingResults)

        // 更新任务状态
        task.status = result.status === 'success' ? 'completed' : 'error'
        task.updatedAt = new Date()

        return result
    }

    async cancelTask(id: string): Promise<void> {
        await this.simulateDelay()
        this.simulateError('cancelTask')

        // 更新任务状态为取消
        for (const dataset of this.datasets.values()) {
            const task = dataset.tasks.find(t => t.id === id)
            if (task) {
                task.status = 'idle' // 重置为空闲状态
                task.updatedAt = new Date()
                return
            }
        }

        throw new Error(`Task with id ${id} not found`)
    }

    async getTaskStatus(taskId: string): Promise<TaskStatusInfo> {
        await this.simulateDelay()
        this.simulateError('getTaskStatus')

        const config = this.getCurrentConfig()

        // 模拟不同的任务状态
        const statuses: TaskStatusInfo['status'][] = ['idle', 'running', 'completed', 'error']
        const status = config.mode === 'error' ? 'error' : 'completed'

        return {
            id: taskId,
            status,
            progress: status === 'completed' ? 100 : Math.floor(Math.random() * 80) + 10,
            message: status === 'error' ? 'Task failed due to mock error' : 'Task completed successfully',
            currentStep: status === 'completed' ? 'Finished' : 'Processing',
            totalSteps: 5,
            startTime: new Date(Date.now() - 120000), // 2分钟前开始
            estimatedCompletion: status === 'completed' ? new Date() : new Date(Date.now() + 60000)
        }
    }

    async getTaskResults(taskId: string): Promise<TaskResult[]> {
        await this.simulateDelay()
        this.simulateError('getTaskResults')

        const results = this.taskResults.get(taskId)
        if (!results || results.length === 0) {
            // 如果没有结果，生成一个默认结果
            const defaultResult = this.dataGenerator.generateTaskResult(taskId, 'detection')
            this.taskResults.set(taskId, [defaultResult])
            return [defaultResult]
        }

        return [...results]
    }

    async getTasksWithPagination(datasetId: string, pagination?: PaginationOption): Promise<PaginatedResponse<Task>> {
        await this.simulateDelay()
        this.simulateError('getTasksWithPagination')

        const tasks = await this.getTasks(datasetId)
        const page = pagination?.page || 1
        const pageSize = pagination?.pageSize || 10
        const startIndex = (page - 1) * pageSize
        const endIndex = startIndex + pageSize

        const items = tasks.slice(startIndex, endIndex)

        return {
            items,
            total: tasks.length,
            page,
            pageSize,
            hasNext: endIndex < tasks.length,
            hasPrev: page > 1
        }
    }

    // 健康检查
    async healthCheck(): Promise<{ status: string; timestamp: string }> {
        await this.simulateDelay()

        const config = this.getCurrentConfig()

        return {
            status: config.mode === 'error' ? 'unhealthy' : 'healthy',
            timestamp: new Date().toISOString()
        }
    }
}

// 创建增强模拟API实例
export const enhancedMockApi = new EnhancedMockApiClient()

// 根据开发工具配置返回适当的API客户端
export const getEnhancedApiClient = (): ExtendedApiClient => {
    if (typeof window !== 'undefined') {
        const devStore = useDevToolsStore.getState()
        if (devStore.useMockApi) {
            console.log('🎭 Using Enhanced Mock API with mode:', devStore.mockDataMode)
            return enhancedMockApi
        }
    }

    // 如果不使用模拟API，返回真实API客户端
    // 这里应该导入真实的API客户端
    return enhancedMockApi // 临时返回模拟API
}

export default enhancedMockApi